﻿

namespace Hidistro.Membership.Context
{
    using Hidistro.Core;
    using Hidistro.Core.Configuration;
    using Hidistro.Core.Enums;
    using Hidistro.Core.Urls;
    using System;
    using System.Configuration;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.Security;
    

    public class HiHttpModule : IHttpModule
    {
        private bool applicationInstalled;
        private ApplicationType currentApplicationType;
        private static readonly Regex urlReg = new Regex("(loginentry.aspx|login.aspx|logout.aspx|resourcenotfound.aspx|verifycodeimage.aspx|SendPayment.aspx|PaymentReturn_url|PaymentNotify_url|InpourReturn_url|InpourNotify_url)", RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);

        private void Application_AuthorizeRequest(object source, EventArgs e)
        {
            if (this.currentApplicationType != ApplicationType.Installer)
            {
                HttpApplication application = (HttpApplication)source;
                HttpContext context = application.Context;
                HiContext current = HiContext.Current;
                if (context.Request.IsAuthenticated)
                {
                    string name = context.User.Identity.Name;
                    if (name != null)
                    {
                        string[] rolesForUser = Roles.GetRolesForUser(name);
                        if ((rolesForUser != null) && (rolesForUser.Length > 0))
                        {
                            current.RolesCacheKey = string.Join(",", rolesForUser);
                        }
                    }
                }
            }
        }

        private void Application_BeginRequest(object source, EventArgs e)
        {
            this.currentApplicationType = HiConfiguration.GetConfig().AppLocation.CurrentApplicationType;
            HttpApplication application = (HttpApplication)source;
            HttpContext context = application.Context;
            if (context.Request.RawUrl.IndexOfAny(new char[] { '<', '>', '\'', '"' }) != -1)
            {
                context.Response.Redirect(context.Request.RawUrl.Replace("<", "%3c").Replace(">", "%3e").Replace("'", "%27").Replace("\"", "%22"), false);
            }
            else
            {
                this.CheckInstall(context);
                if (this.currentApplicationType != ApplicationType.Installer)
                {
                    CheckSSL(HiConfiguration.GetConfig().SSL, context);
                    HiContext.Create(context, new UrlReWriterDelegate(HiHttpModule.ReWriteUrl));
                }
            }
        }

        private void CheckInstall(HttpContext context)
        {
            if ((this.currentApplicationType == ApplicationType.Installer) && this.applicationInstalled)
            {
                context.Response.Redirect(Globals.GetSiteUrls().Home, false);
            }
            else if (!(this.applicationInstalled || (this.currentApplicationType == ApplicationType.Installer)))
            {
                context.Response.Redirect(Globals.ApplicationPath + "/installer/default.aspx", false);
            }
        }

        private static void CheckSSL(SSLSettings ssl, HttpContext context)
        {
            if (ssl == SSLSettings.All)
            {
                Globals.RedirectToSSL(context);
            }
        }

        public void Dispose()
        {
            if (this.currentApplicationType != ApplicationType.Installer)
            {
                Hidistro.Core.Jobs.Jobs.Instance().Stop();
            }
        }

        public void Init(HttpApplication application)
        {
            if (null != application)
            {
                application.BeginRequest += new EventHandler(this.Application_BeginRequest);
                application.AuthorizeRequest += new EventHandler(this.Application_AuthorizeRequest);
                //staticize
                application.BeginRequest += new EventHandler(BeginRequest);
                this.applicationInstalled = ConfigurationManager.AppSettings["Installer"] == null;
                this.currentApplicationType = HiConfiguration.GetConfig().AppLocation.CurrentApplicationType;
                this.CheckInstall(application.Context);
                if (this.currentApplicationType != ApplicationType.Installer)
                {
                    Hidistro.Core.Jobs.Jobs.Instance().Start();
                    ExtensionContainer.LoadExtensions();
                }
            }
        }
        public void BeginRequest(object sender, EventArgs e)
        {
            //Log.logSave("BeginRequest 进入");
            
            HttpApplication application = sender as HttpApplication;
            HttpContext context = application.Context;

            
            if (context.Request.QueryString["Staticize"] != null)
              return;

            string tPrePath =  gloalvar.GetPrePath();

            if (context.Request.HttpMethod == "GET" && context.Request.Path == "/SubCategory.aspx")
            {
                int Categoryid = 0;
                int SubCategoryid = 0;
                string TopRewrite = null;
                string SubRewrite = null;
                 if (context.Request.QueryString["categoryId"] != null)
                {
                    int categoryId;
                    if (int.TryParse(context.Request.QueryString["categoryId"], out categoryId))
                    {
                        JSShop.Model.Hishop_Categories info = new Juse.Interface.CategoryBrowser().GetCategoryInfo(categoryId);
                        if (info == null) return;
                        if (info.ParentCategoryId == 0)
                        {
                            if (context.Request.RawUrl.IndexOf("?") == -1) return;
                            Categoryid = info.CategoryId;
                            TopRewrite = info.RewriteName;
                        }
                        else
                        {
                            Categoryid = info.ParentCategoryId.Value;
                            SubCategoryid = info.CategoryId;
                            TopRewrite = info.ParentRewriteName;
                            SubRewrite = info.RewriteName;
                        }
                    }
                    else return;
                }
                else if (context.Request.QueryString["rewrite"] != null)
                {
                    Hidistro.Entities.Commodities.CategoryInfo info = Hidistro.SaleSystem.Catalog.CategoryBrowser.GetCategoryByRewrite(context.Request.QueryString["rewrite"]);
                    if (info == null) return;
                    if (info.ParentCategoryId == 0)
                    {
                        //输入http://www.x-juse.com/it_taotao，时没有？也应该定位静态页
                        if (context.Request.RawUrl.IndexOf("?") == -1) return;
                        Categoryid = info.CategoryId;
                        TopRewrite = info.RewriteName;
                    }
                    else
                    {
                        if (info.ParentRewriteName != context.Request.QueryString["toprewrite"]) return;
                        Categoryid = info.ParentCategoryId.Value;
                        SubCategoryid = info.CategoryId;
                        TopRewrite = info.ParentRewriteName;
                        SubRewrite = info.RewriteName;
                    }
                }
                else return;
                    //string path = "/" + TopRewrite + (SubRewrite == null ? "" : ("/" + SubRewrite)) + "/Categoryid-" + Categoryid + "_SubCategoryid-" + SubCategoryid;
                    //path += "_feature-" + (string.IsNullOrEmpty(context.Request.QueryString["feature"]) ? "0" : context.Request.QueryString["feature"]);
                    //path += "_Brand-" + (string.IsNullOrEmpty(context.Request.QueryString["brand"]) ? "0" : context.Request.QueryString["brand"]);
                    //path += "_filter-" + (string.IsNullOrEmpty(context.Request.QueryString["filter"]) ? "0" : context.Request.QueryString["filter"]);
                    //path += "_rank-" + (string.IsNullOrEmpty(context.Request.QueryString["rank"]) ? "0" : context.Request.QueryString["rank"]);



                string path = "";

                if (string.IsNullOrEmpty(tPrePath) ==false)
                {
                    path += "/" + tPrePath;
                }

                path += "/" + TopRewrite + "/C" + Categoryid + "S" + SubCategoryid;
                path += "F" + (string.IsNullOrEmpty(context.Request.QueryString["feature"]) ? "0" : context.Request.QueryString["feature"]);
                path += "B" + (string.IsNullOrEmpty(context.Request.QueryString["brand"]) ? "0" : context.Request.QueryString["brand"]);
                path += "F" + (string.IsNullOrEmpty(context.Request.QueryString["filter"]) ? "0" : context.Request.QueryString["filter"]);
                path += "R" + (string.IsNullOrEmpty(context.Request.QueryString["rank"]) ? "0" : context.Request.QueryString["rank"]);

                if (!string.IsNullOrEmpty(context.Request.QueryString["pn"]))
                {
                    int pn;
                    if (int.TryParse(context.Request.QueryString["pn"], out pn) && pn > 1) path += "P" + pn;
                }
                path += ".html";
                if (System.IO.File.Exists(context.Server.MapPath("~" + path)))
                {
                    context.Response.Redirect(path);
                }
            }
            else if(context.Request.HttpMethod == "GET" && context.Request.Path.Contains("/BrandDetails.aspx"))
            {
                //http://localhost:39704/brand/brand_detail-131.htm?cid=0&filter=2&rank=0&Staticize=1
                //Brand_detail-131_cid-0_filter-2_rank-0.html
               // string path = "/brand/";
                string path = "";
                if (string.IsNullOrEmpty(tPrePath) == false)
                {
                    path += "/" + tPrePath;
                }

                path += "/brand/";
                    if (string.IsNullOrEmpty(context.Request.QueryString["brandId"]))
                { }
                else
                {
                    path += "B" + context.Request.QueryString["brandId"];
                    path += "C" + (string.IsNullOrEmpty(context.Request.QueryString["cia"]) ? "0" : context.Request.QueryString["cia"]);
                    path += "F" + (string.IsNullOrEmpty(context.Request.QueryString["filter"]) ? "0" : context.Request.QueryString["filter"]);
                    path += "R" + (string.IsNullOrEmpty(context.Request.QueryString["rank"]) ? "0" : context.Request.QueryString["rank"]);
                    if (!string.IsNullOrEmpty(context.Request.QueryString["pn"]))
                    {
                        int pn;
                        if (int.TryParse(context.Request.QueryString["pn"], out pn) && pn > 1) path += "P" + pn;
                    }
                    path += ".html";
                }
                if (System.IO.File.Exists(context.Server.MapPath("~" + path)))
                {
                    context.Response.Redirect(path);
                }
                
            }
        }

        private static bool ReWriteUrl(HttpContext context)
        {
            string path = context.Request.Path;
            string filePath = UrlReWriteProvider.Instance().RewriteUrl(path, context.Request.Url.Query);
            if (filePath != null)
            {
                string queryString = null;
                int index = filePath.IndexOf('?');
                if (index >= 0)
                {
                    queryString = (index < (filePath.Length - 1)) ? filePath.Substring(index + 1) : string.Empty;
                    filePath = filePath.Substring(0, index);
                }
                context.RewritePath(filePath, null, queryString);
            }
            return (filePath != null);
        }

        public string ModuleName
        {
            get
            {
                return "HiHttpModule";
            }
        }


    }
}

